package com.qfmy.app.service.impl.novel;

import com.qfmy.app.config.ThreadPoolConfig;
import com.qfmy.app.mapper.novel.BookMapper;
import com.qfmy.app.mapper.novel.RatingMapper;
import com.qfmy.app.service.novel.RatingService;
import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.novel.Rating;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;

/**
 * @author 清风明月
 * @Package com.qfmy.app.service.impl.novel
 * @date 2025/4/15
 * @description 评分
 */
@Service
@SuppressWarnings("all")
public class RatingServiceImpl implements RatingService {

    /**
     * 注入mapper
     */
    @Resource
    private RatingMapper ratingMapper;
    /**
     * 注入bookMapper
     */
    @Resource
    private BookMapper bookMapper;

    /**
     * 保存评分
     * @param bookId
     * @param score
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRating(Long bookId, Double score) {
        //获取当前用户id
        Integer userId = getUserId();
        //保存评分
        Rating rating = new Rating();
        rating.setUserId(userId);
        rating.setBookId(Math.toIntExact(bookId));
        rating.setScore(score);
        //异步保存评分
        CompletableFuture.runAsync(() -> ratingMapper.insert(rating), ThreadPoolConfig.executorService);
        //异步更新小说评分
        CompletableFuture.runAsync(() -> bookMapper.updateBookByBookId(bookId, score), ThreadPoolConfig.executorService);
    }

    /**
     * 获取当前用户id
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private Integer getUserId() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return loginUser.getUserId();
    }
}
